﻿using MES.Desktop.Entities;
using MES.Desktop.IDataAccess;
using MES.Desktop.IService;
using MES.Desktop.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MES.Desktop.Service
{
    public class MaterialService : ServiceBase, IMaterialService
    {
        IMaterialAccess _materialAccess;
        public MaterialService(IMaterialAccess materialAccess)
        {
            _materialAccess = materialAccess;
        }

        #region 物料分类
        public bool CheckClassName(string name, int id)
        {
            string json = _materialAccess.CheckClassName(name, id);
            return this.GetResult<bool>(json);
        }

        public int DeleteClass(string[] ids)
        {
            string ids_json = System.Text.Json.JsonSerializer.Serialize(ids);
            string json = _materialAccess.DeleteClass(ids_json);
            var result = JsonUtil.Deserializer<ApiDataResult<int>>(json);

            if (result == null)
                throw new Exception("物料分类数据删除失败!");
            if (!result.Success)
                throw new Exception(result.Message);
            if (result.Data == 0)
                throw new Exception("未删除任何数据");

            return result.Data;
        }

        public IEnumerable<MaterialClassEntity> GetClassAll(string key = "")
        {
            string json = _materialAccess.GetClassAll(key);
            var result = JsonUtil.Deserializer<ApiDataResult<MaterialClassEntity[]>>(json);
            if (result == null)
                throw new Exception("物料分类数据获取失败!");
            if (!result.Success)
                throw new Exception(result.Message);

            return result.Data;
        }

        public int UpdateClass(MaterialClassEntity m_class)
        {
            string m_json = System.Text.Json.JsonSerializer.Serialize(m_class);
            string json = _materialAccess.UpdateClass(m_json);
            var result = JsonUtil.Deserializer<ApiDataResult<int>>(json);

            if (result == null)
                throw new Exception("物料分类数据更新失败!");
            if (!result.Success)
                throw new Exception(result.Message);
            if (result.Data == 0)
                throw new Exception("未更新任何数据");

            return result.Data;
        }
        #endregion
    }
}
